package com.kly.cashmall.module.web;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import androidx.annotation.Nullable;

import com.kly.cashmall.R;
import com.kly.cashmall.base.BaseBarActivity;
import com.kly.cashmall.base.ParamsBuilder;
import com.kly.cashmall.module.repay.RepayResultActivity;
import com.kly.cashmall.services.BaseRequest;
import com.kly.cashmall.services.Params;
import com.kly.cashmall.utils.data.TextUtil;
import com.kly.cashmall.utils.function.ToastUtil;


/**
 * @author
 */
public class WebViewActivity extends BaseBarActivity {

    public static final String TITLE = "TITLE";
    public static final String URL = "URL";
    public static final String DATA = "DATA";

    private WebView webCommon;
    private ProgressBar progressBar;

    private String needHandleBack;

    @Override
    protected void setView(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_web_view);
        webCommon = bindView(R.id.web_common);
        progressBar = bindView(R.id.webview_progress);
        doCommonSetting();
        addProgressChromeClient();

        addWebViewClient();
        Intent intent = getIntent();
        String title = intent.getStringExtra(TITLE);
        String url = intent.getStringExtra(URL);
        boolean data = intent.getBooleanExtra(DATA, false);
        if (!TextUtil.isEmpty(url)) {
            if (data) {
                webCommon.loadData(url, "text/html", "UTF-8");
            } else {
                loadUrl(webCommon, getHeader(), url);
            }
        }
        setTitle(title);
    }

    @Override
    protected void loadData() {

    }

    private String getHeader() {
        return ParamsBuilder.create(new Params(), this);
    }


    @JavascriptInterface
    public void showToast(String msg) {
        ToastUtil.showAppToast(msg);
    }

    /**
     * 通用设置
     */
    private void doCommonSetting() {
        webCommon.addJavascriptInterface(this, "android");
        WebSettings set = webCommon.getSettings();
        set.setAppCacheEnabled(false);
        set.setAppCachePath(this.getCacheDir().getAbsolutePath());
        set.setDomStorageEnabled(true);
        set.setJavaScriptEnabled(true);
        set.setJavaScriptCanOpenWindowsAutomatically(true);
        set.setRenderPriority(WebSettings.RenderPriority.HIGH);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            set.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            set.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        set.setUseWideViewPort(true);
        set.setLoadWithOverviewMode(true);
        set.setAppCacheMaxSize(8388608L);
        set.setGeolocationEnabled(true);
        set.setAllowFileAccess(true);
        set.setBlockNetworkImage(false);
        set.setSupportZoom(true);
        set.setBuiltInZoomControls(true);
        set.setTextZoom(100);
        set.setAllowContentAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            set.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        set.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    private void addProgressChromeClient() {
        webCommon.setWebChromeClient(new ProgressWebChrome(webCommon, progressBar) {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title != null) {
                    setTitle(title);
                }
            }
        });
    }

    private void addWebViewClient() {
        webCommon.setWebViewClient(new WebViewClient() {
            @TargetApi(21)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String url = request.getUrl().toString();
                return overideUrlLoading(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return overideUrlLoading(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                if (url.contains("allowBackToCashBar")) {
                    startActivity(RepayResultActivity.callIntent(getActivity(), getIntent().getStringExtra("billNo"), Integer.valueOf(getIntent().getStringExtra("type"))));
                    finish();
                }
            }
        });
    }

    private boolean overideUrlLoading(WebView view, String url) {
        if (url.startsWith("bytedance://")) {
            view.stopLoading();
            return true;
        }


        if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
            view.reload();
            return true;
        } else {
            view.loadUrl(url);
            return false;
        }

    }

    @Override
    public void onBackPressed() {
        if (TextUtil.isEmpty(needHandleBack)) {
            super.onBackPressed();
        } else {
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webCommon.canGoBack()) {
            if (TextUtil.isEmpty(needHandleBack)) {
                webCommon.goBack();// 返回前一个页面
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static Intent callIntent(Context context, String title, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(TITLE, title);
        intent.putExtra(URL, url);
        return intent;
    }

    public static Intent callIntent(Context context, String title, String url, boolean data) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(TITLE, title);
        intent.putExtra(URL, url);
        intent.putExtra(DATA, data);
        return intent;
    }

    public static Intent callIntent(Context context, String title, String url, boolean data, String type, String billNo) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(TITLE, title);
        intent.putExtra(URL, url);
        intent.putExtra(DATA, data);
        intent.putExtra("type", type);
        intent.putExtra("billNo", billNo);
        return intent;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void loadUrl(WebView view, String header, String url) {
        StringBuilder finalUrl = new StringBuilder(url);
        if (url.contains("contactUs")) {
            if (url.contains("?")) {
                finalUrl.append("&");
            } else {
                finalUrl.append("?");
            }
            finalUrl.append("basicParams=");
            finalUrl.append(header);
            finalUrl.append("&");
            finalUrl.append("host=" + BaseRequest.baseUrl);
        }
        view.loadUrl(finalUrl.toString());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        setResult(10001);
    }
}
